"use client"

import { useState, useEffect } from "react"
import { Department, User } from "@/types/admin"
import { useAdminStore } from "@/lib/store"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"

const formSchema = z.object({
  name: z.string().min(1, "部门名称不能为空"),
  parentId: z.string().optional(),
  managerId: z.string().optional(),
})

type FormValues = z.infer<typeof formSchema>

interface DepartmentDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  department?: Department
  users: User[]
}

export function DepartmentDialog({
  open,
  onOpenChange,
  department,
  users,
}: DepartmentDialogProps) {
  const { departments, addDepartment, updateDepartment } = useAdminStore()
  const isEditing = !!department

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: department?.name || "",
      parentId: department?.parent?.id || "none",
      managerId: department?.manager?.id || "none",
    },
  })

  useEffect(() => {
    if (department) {
      form.reset({
        name: department.name,
        parentId: department.parent?.id || "none",
        managerId: department.manager?.id || "none",
      })
    } else {
      form.reset({
        name: "",
        parentId: "none",
        managerId: "none",
      })
    }
  }, [department, form])

  const onSubmit = (values: FormValues) => {
    const parentDepartment = values.parentId && values.parentId !== "none"
      ? departments.find((d) => d.id === values.parentId)
      : undefined

    const manager = values.managerId && values.managerId !== "none"
      ? users.find((u) => u.id === values.managerId)
      : undefined

    const departmentData = {
      name: values.name,
      parent: parentDepartment,
      manager: manager,
    }

    if (isEditing && department) {
      updateDepartment(department.id, departmentData)
    } else {
      addDepartment(departmentData)
    }

    onOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{isEditing ? "编辑部门" : "新增部门"}</DialogTitle>
          <DialogDescription>
            {isEditing
              ? "修改部门信息，点击保存确认更改。"
              : "添加新部门，填写完成后点击创建。"}
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>部门名称</FormLabel>
                  <FormControl>
                    <Input placeholder="输入部门名称" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="parentId"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>上级部门</FormLabel>
                  <Select
                    onValueChange={field.onChange}
                    value={field.value}
                    defaultValue="none"
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="选择上级部门" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="none">无</SelectItem>
                      {departments
                        .filter((d) => d.id !== department?.id)
                        .map((dept) => (
                          <SelectItem key={dept.id} value={dept.id}>
                            {dept.name}
                          </SelectItem>
                        ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="managerId"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>部门主管</FormLabel>
                  <Select
                    onValueChange={field.onChange}
                    value={field.value}
                    defaultValue="none"
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="选择部门主管" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="none">未指定</SelectItem>
                      {users.map((user) => (
                        <SelectItem key={user.id} value={user.id}>
                          {user.name} ({user.employeeId})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter>
              <Button type="submit">
                {isEditing ? "保存" : "创建"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
} 